/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;

/**
 * @author Mht
 * @date May 31, 2016
 */
@Log4j
public class HttpsUtil {

	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputString) {

		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			TrustManager[] tm = { new HttpsTrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new SecureRandom());

			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				conn.connect();
			}

			if (StringUtils.isNotEmpty(outputString)) {
				OutputStream outputStream = conn.getOutputStream();
				outputStream.write(outputString.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = "";

			while (StringUtils.isNotEmpty(str = bufferedReader.readLine())) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();

			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("Https Request IO Exception : " + e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			log.error("Https Request NoSuchAlgorithm Exception : " + e.getMessage());
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			log.error("Https Request NoSuchProvider Exception : " + e.getMessage());
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			log.error("Https Request KeyManagement Exception : " + e.getMessage());
		}
		return jsonObject;
	}
}
